package vns.server;

import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;
import com.google.gdata.client.authn.oauth.OAuthSigner;
import com.google.gdata.client.calendar.CalendarQuery;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.Person;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.EventEntry;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.google.api.client.auth.oauth.OAuthCallbackUrl;
import com.google.api.client.googleapis.auth.oauth.GoogleOAuthDomainWideDelegation.Url;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.api.oauth.OAuthRequestException;
import com.google.appengine.api.oauth.OAuthService;
import com.google.appengine.api.oauth.OAuthServiceFactory;
import com.google.appengine.api.oauth.OAuthServiceFailureException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URLConnection;
import java.net.URL;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import vns.client.service.CalendarAllService;
import vns.shared.CalendarEventEntryDTO;

@SuppressWarnings("serial")
public class CalendarAllServiceImpl extends RemoteServiceServlet implements
		CalendarAllService {
	
	@Override
	public List<CalendarEventEntryDTO> loadEvenFeed() throws IOException {

//		User user = null;
//        try {
//            OAuthService oauth = OAuthServiceFactory.getOAuthService();
//            user = oauth.getCurrentUser();
//    		System.out.print("AuthDomain:" + user.getAuthDomain());
//    		System.out.print("Id:" + user.getUserId());
//
//        } catch (OAuthRequestException e) {
//        	System.out.print("duongtannghia OAuthRequestException | ");
//        	System.out.print(e.toString());
//            // The consumer made an invalid OAuth request, used an access token that was
//            // revoked, or did not provide OAuth information.
//            // ...
//        }
//		
//		List<CalendarEventEntryDTO> listDTO = new ArrayList<CalendarEventEntryDTO>();
//		try {
//		URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/private/full");
//
//		CalendarQuery myQuery = new CalendarQuery(feedUrl);
//		myQuery.setMinimumStartTime(DateTime.parseDateTime("2011-04-01T00:00:00"));
//		myQuery.setMaximumStartTime(DateTime.parseDateTime("2011-04-30T23:59:59"));
//
//		com.google.gdata.client.calendar.CalendarService myService = 
//			new com.google.gdata.client.calendar.CalendarService("exampleCo-vnsmart-crm-1");
//			myService.setUserCredentials("duongtannghia@gmail.com", "bapnuong");
//
//		// Send the request and receive the response:
//			CalendarEventFeed resultFeed;
//			resultFeed = myService.query(myQuery, CalendarEventFeed.class);
//			for(CalendarEventEntry evenFeed : resultFeed.getEntries()){
//				CalendarEventEntryDTO newDTO = new CalendarEventEntryDTO(
//						evenFeed.getId(), 
//						evenFeed.getTitle().toString(), 
//						evenFeed.getContent().toString());
//				listDTO.add(newDTO);
//			}
//		} catch (ServiceException e) {
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		CalendarService myService = new CalendarService("");
//		try {
//			myService.setUserCredentials("duongtannghia@gmail.com", "bapnuong");
//		} catch (AuthenticationException e) {
//			// TODO Auto-generated catch block
//			System.out.print("Ngu ngu");
//			e.printStackTrace();
//		}
//		URL postUrl =
//			  new URL("http://www.google.com/calendar/feeds/liz@gmail.com/private/full");
//			EventEntry myEntry = new EventEntry();
//
//			myEntry.setTitle(new PlainTextConstruct("Tennis with Darcy"));
//			myEntry.setContent(new PlainTextConstruct("Meet for a quick lesson."));
//
//			Person author = new Person("Elizabeth Bennet", null, "liz@gmail.com");
//			myEntry.getAuthors().add(author);
//
//			DateTime startTime = DateTime.parseDateTime("2006-04-17T15:00:00-08:00");
//			DateTime endTime = DateTime.parseDateTime("2006-04-17T17:00:00-08:00");
//			When eventTimes = new When();
//			eventTimes.setStartTime(startTime);
//			eventTimes.setEndTime(endTime);
//			myEntry.addTime(eventTimes);
//
//			// Send the request and receive the response:
//			try {
//				EventEntry insertedEntry = myService.insert(postUrl, myEntry);
//			} catch (ServiceException e) {
//				// TODO Auto-generated catch block
//				e.printStackTrace();
//			}

		List<CalendarEventEntryDTO> listDTO = new ArrayList<CalendarEventEntryDTO>();
		try {

			// Set up the URL and the object that will handle the connection:
			URL feedUrl = new URL(
					"https://www.google.com/calendar/feeds/default/private/full");
			CalendarService myService = new CalendarService(
					"vnsmart-crm");

			String str_date = "20-04-2011";
			DateFormat formatter;
			Date date;
			formatter = new SimpleDateFormat("dd-MM-yy");
			date = (Date) formatter.parse(str_date);
			java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
			
			// parametters
			GoogleOAuthParameters parameters = new GoogleOAuthParameters();
//			parameters.setOAuthConsumerKey(consumerKey);
//			parameters.setOAuthConsumerSecret(consumerSecret);
			
//			myService.setUserCredentials("duongtannghia", "bapnuong");
			myService.setUserToken("4/OmcdPQqQ4uHHfp3gOg");
			
			
			//https://www.google.com/accounts/OAuthGetRequestToken
			
			// Send the request and receive the response:
			CalendarEventFeed myFeed = myService.getFeed(feedUrl,
					CalendarEventFeed.class);
			
			List<CalendarEventEntry> listEvenEntries = myFeed.getEntries();
			for(CalendarEventEntry ele : listEvenEntries){
				CalendarEventEntryDTO eleDTO = new CalendarEventEntryDTO();
				//
				eleDTO.setTitle(ele.getTitle().getPlainText());
				listDTO.add(eleDTO);
			}

		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return listDTO;
	}
	
	/**
	 * Sends an HTTP GET request to a url
	 * 
	 * @param endpoint
	 *            - The URL of the server. (Example:
	 *            " http://www.yahoo.com/search")
	 * @param requestParameters
	 *            - all the request parameters (Example:
	 *            "param1=val1&param2=val2"). Note: This method will add the
	 *            question mark (?) to the request - DO NOT add it yourself
	 * @return - The response from the end point
	 */
	public static String sendGetRequest(String endpoint,
			String requestParameters) {
		String result = null;
		if (endpoint.startsWith("http://") || endpoint.startsWith("https://")) {
			// Send a GET request to the servlet
			try {
				// Construct data
				StringBuffer data = new StringBuffer();

				// Send data
				String urlStr = endpoint;
				if (requestParameters != null && requestParameters.length() > 0) {
					urlStr += "?" + requestParameters;
				}
				URL url = new URL(urlStr);
				URLConnection conn = url.openConnection();

				// Get the response
				BufferedReader rd = new BufferedReader(new InputStreamReader(
						conn.getInputStream()));
				StringBuffer sb = new StringBuffer();
				String line;
				while ((line = rd.readLine()) != null) {
					sb.append(line);
				}
				rd.close();
				result = sb.toString();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

}
